package com.example.asynctask;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //private static final String TAG = MainActivity.class.getSimpleName();
    Button btn_downloadfile;
    Button btn_downloadpic;
    ImageView iv;
    ProgressBar bar;
    TextView textView;
    private DownLoaderAsyncTask downLoaderAsyncTask;
    private DownloadpicAsyncTask downloadpicAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();

        btn_downloadfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "开始下载人脸图片文件", Toast.LENGTH_SHORT).show();
                /*downLoaderAsyncTask = new DownLoaderAsyncTask();
                //downLoaderAsyncTask.execute("xxxx","xxx");
                String apk = "http://10.0.0.204:8090/face/getWorkerHeadFace/a0ed10c4e74b4d2aa8797a0c5a4c9d57";
                downLoaderAsyncTask.execute(apk);*/
                String url = "http://10.0.0.204:8090/face/getWorkerHeadFace/a0ed10c4e74b4d2aa8797a0c5a4c9d57";
                Bitmap bitmap = getface(url);
                iv.setImageBitmap(bitmap);

            }
        });

        btn_downloadpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadpicAsyncTask = new DownloadpicAsyncTask();
                String s = "https://deak.top/wp-content/themes/Sakurairo/images/img_article/01.png";
                downloadpicAsyncTask.execute(s);
            }
        });

    }


    public Bitmap getface(String url) {
        Bitmap bitmap = null;
        new Thread() {
            @Override
            public void run() {

            }
        }.start();
        try {
            URL resurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) resurl.openConnection();
            conn.getDoInput();
            conn.setConnectTimeout(0);
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            //return bitmap;
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 初始化控件
     */
    private void initview() {
        btn_downloadfile = findViewById(R.id.startButton);
        btn_downloadpic = findViewById(R.id.cancelButton);
        bar = findViewById(R.id.progressBar);
        textView = findViewById(R.id.textView);
        iv = findViewById(R.id.imageView);
    }

    /**
     * 构造函数AsyncTask<Params, Progress, Result>参数说明:
     * Params   启动任务执行的输入参数
     * Progress 后台任务执行的进度
     * Result   后台计算结果的类型
     */
    @SuppressLint("StaticFieldLeak")
    private class DownLoaderAsyncTask extends AsyncTask<String, Integer, Boolean> {
        //onPreExecute()方法用于在执行异步任务前,主线程做一些准备工作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            textView.setText("下载中");
            btn_downloadfile.setText("下载中");
            bar.setProgress(0);
        }

        //doInBackground()方法用于在执行异步任务,不可以更改主线程中UI
        @Override
        public Boolean doInBackground(String... params) {
            if (params != null && params.length > 0) {
                String url = params[0];
                try {
                    URL requesturl = new URL(url);
                    HttpURLConnection con = (HttpURLConnection) requesturl.openConnection();
                    /*con.setConnectTimeout(10000);
                    con.setReadTimeout(20000);*/
                    InputStream is = con.getInputStream();
                    int contentlenth = con.getContentLength();
                    String filepath = Environment.getExternalStorageDirectory() + File.separator + "test.apk";
                    File file = new File(filepath);
                    if (file.exists()) {
                        file.delete();
                    }
                    int downloadsize = 0;
                    byte[] buff = new byte[2048];
                    int len;
                    OutputStream os = new FileOutputStream(filepath);
                    //不断取数据
                    while ((len = is.read(buff)) != -1) {
                        os.write(buff, 0, len);
                        downloadsize += len;
                        //发送更新进度
                        publishProgress(downloadsize * 100 / contentlenth);
                    }
                    is.close();
                    os.close();
                    return true;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                return false;
            }
            return false;
        }

        //onPostExecute()方法用于异步任务执行完成后,在主线程中执行的操作
        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                textView.setText("下载完成" + Environment.getExternalStorageDirectory() + File.separator + "test");
                btn_downloadfile.setText("下载完成");
                bar.setProgress(0);
            }
        }

        //onProgressUpdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //处理进度
            if (values != null && values.length > 0) {
                bar.setProgress(values[0]);
            }
        }

        //onCancelled()方法用于异步任务被取消时,在主线程中执行相关的操作

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    /**
     * 用于异步下载图片
     */
    @SuppressLint("StaticFieldLeak")
    private class DownloadpicAsyncTask extends AsyncTask<String, Integer, List<Bitmap>> {

        //准备任务
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            textView.setText("准备开始下载图片");
            btn_downloadpic.setText("准备开始下载图片");
            bar.setProgress(0);
        }

        //下载图片和加载图片同时进行时容易出问题
        @Override
        protected List<Bitmap> doInBackground(String... params) {
            List<Bitmap> data = new ArrayList<>();
            if (params != null && params.length > 0) {
                String url = params[0];
                try {
                    URL requesturl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) requesturl.openConnection();
                    conn.setReadTimeout(6000);
                    conn.setConnectTimeout(6000);
                    conn.setRequestMethod("GET");
                    conn.connect();
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream isreadpic = conn.getInputStream();
                        InputStream isdownload = conn.getInputStream();
                        int contentlength = conn.getContentLength();
                        //Bitmap bitmapdata = BitmapFactory.decodeByteArray(isdownload);
                        Bitmap bitmapdata = BitmapFactory.decodeStream(isreadpic);
                        //--------------------下载图片文件----------------------------//
                        /*String filed = Environment.getExternalStorageDirectory() + "/test/";
                        String file = filed + "test.png";
                        //判断你是不是有该文件夹  没有就创建
                        File fileDirectory = new File(filed);
                        if (!fileDirectory.exists()) {
                            fileDirectory.mkdirs();
                        }
                        File filepath = new File(file);
                        OutputStream os = new FileOutputStream(filepath);
                        byte[] filebuff = new byte[2048];
                        int len = -1;
                        while ((len = isdownload.read(filebuff)) != -1) {
                            os.write(filebuff, 0, len);
                        }*/
                        //--------------------下载图片文件----------------------------//

                        //发送更新进度
                        for (int i = 0; i < contentlength; i++) {
                            publishProgress(i);
                        }
                        data.add(bitmapdata);
                        isdownload.close();
                        isreadpic.close();
                        //os.close();
                    } else {
                        Toast.makeText(MainActivity.this, "响应失败", Toast.LENGTH_SHORT).show();
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return data;
        }

        @Override
        protected void onPostExecute(List<Bitmap> res) {
            super.onPostExecute(res);
            if (res != null && res.size() > 0) {
                btn_downloadpic.setText("下载完成");
                textView.setText("图片下载完成");
                iv.setImageBitmap(res.get(0));
                bar.setProgress(0);
            } else {
                Toast.makeText(MainActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show();
            }
        }

        //更新进度条
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            bar.setProgress(values[0]);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

}
